import Axios from 'axios'
import qs from 'qs'
import router from "../router"
import config from '@/config/'

let axios = Axios.create()
axios.interceptors.response.use(function(response){
    return response
},function(error){
    console.log(error)
    let error_result = error.toJSON()
    if(error_result.message.indexOf("timeout") >= 0 ) {
        router.push('error-408')
    }
    return Promise.reject(error)
})

/**
 * post请求
 * @param action
 * @param param
 * @method post OR get
 * @returns {Promise<AxiosResponse<T>>}
 */
export const post = function (action, param) {
    let actions = action.split('/')
    let url = process.env.NODE_ENV === 'production' ? config.baseUrl.pro : config.baseUrl.dev
    let params = {
        pages: actions[0],
        doing: actions[1]
    }
    let send_data = Object.assign(params, param)
    return axios.post(url, qs.stringify(send_data))
}

export const upload = function(action,data,uploading) {
    let actions = action.split('/')
    let url = process.env.NODE_ENV === 'production' ? config.baseUrl.pro : config.baseUrl.dev
    data.append("pages",actions[0])
    data.append("doing",actions[1])
    return axios.post(
        url,
        data,
        {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress:(progress) => {
                uploading({total:progress.total,loaded:progress.loaded})
            }
        }
        )
}

/**
 * get 请求
 * @param action
 * @param param
 * @returns {Promise<AxiosResponse<T>>}
 */
export const get = function (action, param) {
    let actions = action.split('/')
    let url = process.env.NODE_ENV === 'production' ? config.baseUrl.pro : config.baseUrl.dev
    let params = {
        pages: actions[0],
        doing: actions[1]
    }
    let send_data = Object.assign(params, param)
    url += '&' + qs.stringify(send_data)
    return axios.get(url)
}

export default {post, get}
